package com.mangowang.module.main.ui;

/**
 * 文件名 : EarningDetailActivity
 * 创建者 : MangoWang
 * 创建日期 : 2019/11/28 20:06
 * 微信 : MangoWaWang
 * 邮箱 : 763482205@qq.com
 * 描述 : TODO
 */

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.protobuf.InvalidProtocolBufferException;
import com.mangowang.lib.common.base.BaseActivity;
import com.mangowang.lib.common.net.Apis;
import com.mangowang.lib.common.net.NetworkManager;
import com.mangowang.lib.common.net.interfaces.OnRequestCallBack;
import com.mangowang.lib.common.proto.Mystock;
import com.mangowang.lib.common.proto.Transfer;
import com.mangowang.lib.common.util.GsonUtils;
import com.mangowang.lib.common.util.StatusBarUtil;
import com.mangowang.lib.common.util.ValidateUtils;
import com.mangowang.module.main.R;
import com.mangowang.module.main.R2;
import com.mangowang.module.main.adapter.AllowSnAdapter;
import com.mangowang.module.main.bean.AllowSnListBean;
import com.mangowang.module.main.dialog.RecycleViewDialog;
import com.mangowang.module.main.dialog.ShowSelectDialog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import kale.ui.view.dialog.EasyDialog;

public class AllowSnActivity extends BaseActivity {

    Unbinder unbinder;
    @BindView(R2.id.back_iv)
    ImageView backIv;
    @BindView(R2.id.tv_title)
    TextView tvTitle;
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.btn_hua)
    Button btnHua;


    private AllowSnAdapter mAdapter;
    private List<AllowSnListBean> datas = new ArrayList<>();
    private int total;
    private int clickPosition = 0;
//    private int canTotal;
//    private int FirstcanTotal;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_allow_sn);
        unbinder = ButterKnife.bind(this);
        StatusBarUtil.setStatusBarLightMode(this, Color.parseColor("#ffffff"), true);
        tvTitle.setText("选择SN号");
//        canTotal = getIntent().getIntExtra("can_total", 0);
//        FirstcanTotal = getIntent().getIntExtra("can_total", 0);
        initRecyclerView();
        initData();
        backIv.setOnClickListener(v -> finish());
        btnHua.setOnClickListener(v -> {
            if (total == 0) {
                showToast("请先选择划拨SN");
            } else {
                StringBuilder buffer = new StringBuilder();
                StringBuilder buffer2 = new StringBuilder();
                buffer2.append("\n");
                for (int i = 0; i < datas.size(); i++) {
                    for (int j = 0; j < datas.get(i).getSelectedSnList().size(); j++) {
                        buffer.append(datas.get(i).getSelectedSnList().get(j).getSn_code()).append(",");
                    }
                    if (datas.get(i).getSelectedSnList().size() != 0) {
                        buffer2.append(datas.get(i).getShowSnNumber()).append("\n").append("已选").append(datas.get(i).getSelectedSnList().size()).append("台/共").append(datas.get(i).getTotalSnNumber()).append("台").append("\n");
                    }
                }
                String sn_up_code = buffer.substring(0, buffer.length() - 1);
                String sn_code = buffer2.toString();
                Intent intent = new Intent();
                Log.e("sn_up_code", sn_up_code);
                Log.e("sn_code", sn_code);
                intent.putExtra("sn_code", sn_code);
                intent.putExtra("sn_up_code", sn_up_code);
                intent.putExtra("sn_number", String.valueOf(total));
                setResult(700, intent);
                finish();
            }
        });

    }

    private void initData() {
        Transfer.SN.Builder builder = Transfer.SN.newBuilder();
        builder.setGoodId(getIntent().getStringExtra("goods_id"))
                .setGcCode(getIntent().getStringExtra("gc_code"))
                .setPattern(getIntent().getStringExtra("pattern"))
                .setActivation(getIntent().getStringExtra("activation"));
        NetworkManager.INSTANCE.post(Apis.get_sn, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) throws InvalidProtocolBufferException {
                List<Transfer.SN.array> lianBean = Transfer.SN.parseFrom(response).getArrayListList();
                List<Transfer.SN.List> NolianBean = Transfer.SN.parseFrom(response).getOtherListList();
                Log.e("Transfer", Transfer.SN.parseFrom(response).toString());
                // 1.遍历连号的列表
                for (int i = 0; i < lianBean.size(); i++) {
                    AllowSnListBean snListBean = new AllowSnListBean();
                    Transfer.SN.array array = lianBean.get(i);
                    List<Transfer.SN.List> tempList = array.getListList();
                    if (tempList.size() == 1) {
                        snListBean.setShowSnNumber(tempList.get(0).getSnCode());
                    } else {
                        snListBean.setShowSnNumber(tempList.get(0).getSnCode() + "--" + tempList.get(tempList.size() - 1).getSnCode());
                    }
                    snListBean.setTotalSnNumber(String.valueOf(tempList.size()));
                    // 获取有多少个可以给用划拨
                    int canUser = 0;
                    for (int j = 0; j < tempList.size(); j++) {
                        AllowSnListBean.SnMessage snMessage = new AllowSnListBean.SnMessage();
                        snMessage.setId(tempList.get(j).getId());
                        snMessage.setSn_code(tempList.get(j).getSnCode());
                        snMessage.setIs_transfer(tempList.get(j).getIsTransfer());
                        canUser++;
                        snListBean.getSnList().add(snMessage);
                    }
                    snListBean.setUseSnNumber(String.valueOf(canUser));
                    datas.add(snListBean);
                }
                // 2.遍历不连号的列表
                if (ValidateUtils.isValidate(NolianBean)) {
                    AllowSnListBean snListBean = new AllowSnListBean();
                    snListBean.setShowSnNumber("不连号机具");
                    snListBean.setTotalSnNumber(String.valueOf(NolianBean.size()));
                    // 获取有多少个可以给用划拨
                    int canUser = 0;
                    for (int i = 0; i < NolianBean.size(); i++) {
                        AllowSnListBean.SnMessage snMessage = new AllowSnListBean.SnMessage();
                        snMessage.setId(NolianBean.get(i).getId());
                        snMessage.setSn_code(NolianBean.get(i).getSnCode());
                        snMessage.setIs_transfer(NolianBean.get(i).getIsTransfer());
                        canUser++;
                        snListBean.getSnList().add(snMessage);
                    }
                    snListBean.setUseSnNumber(String.valueOf(canUser));
                    datas.add(snListBean);
                }
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                showToast(errorMessage);
            }
        });
    }

    private void initRecyclerView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.setAdapter(mAdapter = new AllowSnAdapter(mContext, datas));
        mAdapter.setEmptyView(R.layout.recycle_empty);
        // 每个item的点击事件
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
//            Log.e("canSelect", "外层初始canTotal: " + canTotal + " ");
            ShowSelectDialog.Builder builder = new ShowSelectDialog.Builder(mContext);
            builder.setOnDialogClickListener((v, type) -> {
                Intent intent = new Intent(mContext, AllowSnListActivity.class);
                intent.putExtra("snData", GsonUtils.serializedToJson(datas.get(position)));
                intent.putExtra("type", type);
                clickPosition = position;
                startActivityForResult(intent,100);


            });
            EasyDialog build = builder.build();
            build.setCancelable(true);
            build.show(getSupportFragmentManager());
        });


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 800) {
            String item = data.getStringExtra("snData");
            AllowSnListBean bean = GsonUtils.deSerializedFromJson(item, AllowSnListBean.class);
            datas.set(clickPosition, bean);
            mAdapter.notifyItemChanged(clickPosition);
            total = 0;
            for (int i = 0; i < datas.size(); i++) {
                Log.e("size", datas.get(i).getSelectedSnList().size() + "");
                total = total + datas.get(i).getSelectedSnList().size();

            }
            if (total == 0) {
                btnHua.setText("确定");
            } else {
                btnHua.setText("确定(共选" + total + "台)");
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}
